package cn.wzvtc.rbac_mp.service.impl;

import cn.wzvtc.rbac_mp.dao.RoleMapper;
import cn.wzvtc.rbac_mp.dao.RoleMenuMapper;
import cn.wzvtc.rbac_mp.dao.UserRoleMapper;
import cn.wzvtc.rbac_mp.dto.RoleBO;
import cn.wzvtc.rbac_mp.entity.Role;
import cn.wzvtc.rbac_mp.entity.RoleMenu;
import cn.wzvtc.rbac_mp.entity.UserRole;
import cn.wzvtc.rbac_mp.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author Shiwei Xu
 * @date 2020/5/26
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

  @Autowired
  private RoleMenuMapper roleMenuMapper;
  @Autowired
  private UserRoleMapper userRoleMapper;

  @Transactional
  @Override
  public void addRole(RoleBO roleBO) {
    // 新增用户
    Role role = new Role();
    BeanUtils.copyProperties(roleBO, role);
    this.save(role);

    // 新增角色权限关系
    addRoleMenu(role.getId(), roleBO.getMenuIds());
  }

  @Transactional
  @Override
  public void updateRole(RoleBO roleBO) {
    // 更新用户
    Role role = new Role();
    BeanUtils.copyProperties(roleBO, role);
    this.updateById(role);

    // 更新角色权限关系
    updateRoleMenu(role.getId(), roleBO.getMenuIds());
  }

  private void addRoleMenu(Long roleId, List<Long> menuIds) {
    // 角色没有一个权限的情况
    if (CollectionUtils.isEmpty(menuIds)) {
      return;
    }
    // 新增角色用户关系
    for (Long menuId : menuIds) {
      RoleMenu roleMenu = new RoleMenu();
      roleMenu.setMenuId(menuId);
      roleMenu.setRoleId(roleId);
      roleMenuMapper.insert(roleMenu);
    }
  }

  private void updateRoleMenu(Long roleId, List<Long> menuIds) {
    // 先删除原先的用户角色关系
    QueryWrapper<RoleMenu> wrapper = new QueryWrapper<>();
    wrapper.eq("role_id", roleId);
    roleMenuMapper.delete(wrapper);

    // 建立新的角色权限管理
    addRoleMenu(roleId, menuIds);
  }

  @Transactional
  @Override
  public void delete(List<Long> ids) {
    // 删除角色
    this.removeByIds(ids);

    // 删除角色权限关系
    // delete from role_menu where role_id in (111, 222, 333)
    QueryWrapper<RoleMenu> wrapper = new QueryWrapper<>();
    wrapper.in("role_id", ids);
    roleMenuMapper.delete(wrapper);

    // 删除用户角色关系
    QueryWrapper<UserRole> wrapper2 = new QueryWrapper<>();
    wrapper2.in("role_id", ids);
    userRoleMapper.delete(wrapper2);
  }
}
